<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never" class="never" :model="form">
        <el-form ref="form">
          <span>标签名称</span>
          <el-input v-model="form.tagName" class="tagName"></el-input>
          <span>状态</span>
          <el-select class="state" v-model="form.state" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-button size="mini" @click="cleanTing">清除</el-button>
          <el-button size="mini" type="primary" @click="searchTing"
            >搜索</el-button
          >
          <el-button
            class="onSubmit"
            type="success"
            icon="el-icon-edit"
            size="small"
            @click="newLabel"
            >新增标签</el-button
          >
        </el-form>

        <!-- 数据记录 -->
        <el-alert :title="totalNum" type="info" show-icon class="dateN">
        </el-alert>

        <!-- 数据表格 -->
        <el-table class="dataTable" :data="tableList" style="width: 100%">
          <el-table-column type="index" label="序号" width="180">
          </el-table-column>

          <el-table-column prop="subjectName" label="所属学科" width="180">
          </el-table-column>

          <el-table-column prop="tagName" label="标签名称"> </el-table-column>

          <el-table-column prop="username" label="创建者"> </el-table-column>

          <el-table-column prop="addDate" label="创建日期">
            <template slot-scope="scope">
              <span>{{ scope.row.addDate | formatTime }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="state" label="状态">
            <template slot-scope="scope">
              <span v-if="scope.row.state == 1">已启用</span>
              <span v-else>已禁用</span>
            </template>
          </el-table-column>

          <el-table-column prop="creatorID" label="操作">
            <template slot-scope="scope">
              <el-button type="text" @click="changeState(scope.row)">
                <span>{{ scope.row.state == 1 ? "禁用" : "启用" }}</span>
              </el-button>
              <el-button
                type="text"
                @click="moDifyThing(scope.row)"
                :disabled="scope.row.state == 1 ? true : false"
                >修改</el-button
              >
              <el-button
                type="text"
                class="modify"
                @click="deleteChange(scope.row)"
                :disabled="scope.row.state == 1 ? true : false"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 分页 -->
    <div class="pageBox">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="query.page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="query.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="Number(totalPage)"
      >
      </el-pagination>
      <!-- 新增/修改弹框 -->
      <el-dialog
        @close="cancelForm"
        :title="isEdit ? '新增目录' : '修改目录'"
        :visible.sync="addLabel"
        width="30%"
      >
        <el-form ref="form" :model="form" label-width="80px" :rules="formRules">
          <el-form-item label="所属学科" prop="areaName">
            <el-select
              v-model="form.areaName"
              placeholder="请选择"
              style="width: 100%"
              @change="valueChange"
            >
              <el-option
                v-for="item in courseList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目录名称" prop="tagName">
            <el-input
              v-model="form.tagName"
              placeholder="请输入目录名称"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancelForm">取 消</el-button>
          <el-button type="primary" @click="submitForm()"
            >确 定</el-button
          ></span
        >
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { list, add, changeState, detail, remove } from '@/api/hmmm/tags.js'
import { simple as subjectsSimple } from '@/api/hmmm/subjects.js'
import dayjs from 'dayjs'
export default {
  name: 'Tags',
  // 时间格式转换
  filters: {
    formatTime (time) {
      return dayjs(time).format('YYYY-MM-DD hh:mm:ss')
    }
  },
  data () {
    // 自定义校验规则
    const validatEarea = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请选择所属学科'))
      }
      callback()
    }
    const validatDirectory = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入标签名称'))
      }
      callback()
    }
    return {
      // 表单验证
      formRules: {
        areaName: [
          { required: true, message: '请选择所属学科', trigger: 'blur' },
          { validator: validatEarea, trigger: blur }
        ],
        tagName: [
          { required: true, message: '请输入标签名称', trigger: 'blur' },
          { validator: validatDirectory, trigger: blur }
        ]
      },
      // 枚举状态
      options: [
        {
          value: '1',
          label: '启用'
        },
        {
          value: '0',
          label: '禁用'
        }
      ],
      tableList: [], // 数据列表
      total: '', // 总条数
      totalPage: '', // 每页总条数
      query: {
        tagName: '', // 标签名称
        page: 1, // 第几页
        pagesize: 10 // 分页显示总条数
      },
      addLabel: false, // 弹框展示
      courseList: [], // 学科表
      form: {
        areaName: '', // 所属学科的校验名
        subjectID: 19, // 学科ID
        tagName: '', // 标签名称
        state: '' // 启用 禁用状态
      },
      disabled: false, // 按钮隐藏与显示
      isEdit: false, // 是否新增/修改目录
      sousform: {} // 定义一个接收搜索数据的对象
    }
  },
  created () {
    // 渲染列表
    this.list()
    // 调用获取学科ID
    this.simple()
  },

  computed: {
    // 总数据条数
    totalNum () {
      return `数据一共  ${this.total}  条`
    }
  },

  methods: {
    // 删除事件
    async deleteChange (row) {
      const confirmRes = await this.$confirm(
        '此操作将永久删除该目录, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (confirmRes === 'cancel') return this.$message('您取消了删除')
      await remove(row)
      this.$message.success('删除成功')
      this.list()
    },

    // 点击新增标签事件
    newLabel () {
      this.addLabel = true
      this.isEdit = true
    },
    // 修改事件
    async moDifyThing (row) {
      this.addLabel = true // 弹框展示
      this.isEdit = false // 新增/修改 目录
      await detail(row)
      this.form.areaName = row.subjectName
      this.form.tagName = row.tagName
    },

    // 禁用/启用状态
    async changeState (row) {
      var data = {
        id: row.id,
        state: Number(!row.state)
      }
      await changeState(data)
        .then((response) => {
          this.$message.success('操作成功!')
          this.list()
        })
        .catch((response) => {
          this.$message.error(status + '失败!')
        })
    },

    // 下拉框获取数据
    valueChange (data) {
      this.form.subjectID = data
    },
    // 点击取消时
    cancelForm () {
      this.addLabel = false
      this.simple()
      this.$refs.form.clearValidate()
      this.form.areaName = ''
      this.form.tagName = ''
    },

    // 点击确定时新增标签
    submitForm () {
      this.$refs.form.validate(async (valid) => {
        if (!valid) return
        await add(this.form)
        this.$message.success('添加标签成功')
        this.list()
        this.addLabel = false
        this.form.areaName = ''
        this.form.tagName = ''
      })
    },

    // 获取标签简单数据
    async simple () {
      const res = await subjectsSimple()
      this.courseList = res.data
      this.$refs.form.clearValidate()
    },

    // 搜索
    async searchTing () {
      this.query.page = 1
      // 重发请求
      // 把表单搜索值合并
      this.sousform = this.form
      const data = {
        tagName: this.sousform.tagName,
        state: this.sousform.state === '' ? null : this.sousform.state,
        page: this.query.page,
        pagesize: this.query.pagesize
      }
      // 发送了一个请求
      const res = await list(data)
      this.tableList = res.data.items
    },

    // 清空表单
    cleanTing () {
      this.form.tagName = ''
      this.form.state = ''
      this.list()
    },

    // 更改每页显示的条数
    handleSizeChange (val) {
      this.query.pagesize = val
      this.list()
    },

    // 点击某一个页码
    handleCurrentChange (val) {
      this.query.page = val
      this.list()
    },

    // 获取列表数据
    async list () {
      const res = await list(this.query)
      // 渲染列表数据
      this.tableList = res.data.items
      this.total = res.data.counts
      this.totalPage = res.data.counts
    }
  }
}
</script>

<style scoped>
.tagName {
  width: 200px;
  margin: 0 50px 0 10px;
}
.state {
  width: 200px;
  margin: 0 10px 0 10px;
}
.onSubmit {
  position: absolute;
  right: 20px;
}
.pageBox {
  position: absolute;
  right: 20px;
}
.never {
  position: relative;
}
.dataTable {
  margin-top: 15px;
}
.dateN {
  margin-top: 20px;
}
</style>
